'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.genCancelNs = undefined;

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _genNs = require('./genNs');

var _removeArrayItem = require('./removeArrayItem');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var id = 0;
var genCancelNs = exports.genCancelNs = function genCancelNs() {
    var namespace = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'genCancelNs' + id++;

    var nsData = (0, _genNs.genNs)();
    return {
        add: function add(ns, cancel) {
            if (typeof ns === 'function') {
                cancel = ns;
                ns = namespace;
            }
            return nsData.add(ns, cancel);
        },
        getCancel: function getCancel(data) {
            var id = data.id;
            return {
                id: id,
                cancel: function cancel() {
                    var item = nsData.getById(id);
                    if (item && item.value[0]) {
                        item.value[0]();
                        item.value[0] = null;
                    }
                    nsData.removeById(id);
                }
            };
        },
        addOne: function addOne(ns, cancel) {
            this.cancel(ns, cancel);
            return this.add(ns, cancel);
        },
        addIfNotExist: function addIfNotExist(ns, cancel) {
            var _nsData$get = nsData.get(ns, cancel),
                _nsData$get2 = (0, _slicedToArray3.default)(_nsData$get, 1),
                data = _nsData$get2[0];

            if (data) {
                return data;
            }
            return this.add(ns, cancel);
        },
        cancel: function cancel() {
            var ns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : namespace;
            var cancel = arguments[1];

            var data = nsData.get(ns, cancel);
            for (var i = 0, il = data.length; i < il; i++) {
                this.getCancel(data[i]).cancel();
            }
        },
        cancelAll: function cancelAll() {
            this.cancel('');
        }
    };
};

exports.default = genCancelNs;